// 简单的前端 Mock API，使用 localStorage 做持久化，便于演示删除/添加/搜索等操作。
// 接口：listImages, detectAndSaveImage, searchImages, deleteImage
// 使用方式与之前相同：import { listImages, detectAndSaveImage, searchImages, deleteImage } from '../utils/mockApi'

const STORAGE_KEY = 'wb_images_v1'

// 使用项目内的静态图片作为示例展示，确保前端能正确显示
import crackImg from '../assets/新能源发电.png'
import oilImg from '../assets/react.svg'

// Helper: load from localStorage
function _loadStore() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return []
    const arr = JSON.parse(raw)
    if (!Array.isArray(arr)) return []
    return arr
  } catch (e) {
    console.warn('mockApi: load error', e)
    return []
  }
}

// Helper: save to localStorage
function _saveStore(arr) {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(arr))
  } catch (e) {
    console.warn('mockApi: save error', e)
  }
}

// Ensure there's some sample data on first run
;(function initDefault() {
  const cur = _loadStore()
  if (cur.length === 0) {
    const sample = [
      {
        id: 'img_1',
        name: 'blade_crack_01.jpg',
        dataUrl: crackImg, // 使用打包后的资源，保证显示为正确示例图片
        url: '',     // optional
        tags: ['裂纹'],
        detections: [{ class: '裂纹', confidence: 0.86, bbox: [10,20,200,180] }],
        createdAt: Date.now() - 1000 * 60 * 60 * 24
      },
      {
        id: 'img_2',
        name: 'blade_oil_01.jpg',
        dataUrl: oilImg,
        tags: ['油污'],
        detections: [{ class: '油污', confidence: 0.78 }],
        createdAt: Date.now() - 1000 * 60 * 60 * 6
      }
    ]
    _saveStore(sample)
  }
})()

// Utility: small delay to simulate async
function _delay(ms = 250) {
  return new Promise(res => setTimeout(res, ms))
}

// List images
export async function listImages() {
  await _delay(120)
  return _loadStore().slice().sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0))
}

// Save / detect (mock)
// Accepts: { name, dataUrl, detections?, tags? }
// Returns saved item
export async function detectAndSaveImage({ name, dataUrl, detections = [], tags = [] }) {
  await _delay(300)
  const store = _loadStore()
  const id = `img_${Date.now()}_${Math.floor(Math.random() * 9999)}`
  const item = {
    id,
    name: name || id,
    dataUrl: dataUrl || '',
    url: '',
    tags: Array.isArray(tags) ? tags : [],
    detections: detections,
    createdAt: Date.now()
  }
  // Prepend so newest appear first
  store.unshift(item)
  _saveStore(store)
  return item
}

// Search images by q (in name) or tag
export async function searchImages({ q = '', tag = '' } = {}) {
  await _delay(180)
  const store = _loadStore()
  const qLower = String(q || '').trim().toLowerCase()
  
  // 按标签筛选
  if (tag && tag !== 'all') {
    const filtered = store.filter(it => {
      // 确保 tags 是数组且包含指定标签
      return Array.isArray(it.tags) && it.tags.some(t => t === tag || t.includes(tag))
    })
    return filtered.sort((a,b) => (b.createdAt||0) - (a.createdAt||0))
  }
  
  // 按关键词搜索
  if (!qLower) return store.slice().sort((a,b) => (b.createdAt||0) - (a.createdAt||0))
  
  return store.filter(it => 
    (it.name || '').toLowerCase().includes(qLower) || 
    (it.description || '').toLowerCase().includes(qLower) ||
    (Array.isArray(it.tags) && it.tags.join(',').toLowerCase().includes(qLower))
  )
}

// Delete image by id. Returns { ok: true } or { ok: false, reason }
export async function deleteImage(id) {
  if (!id) return { ok: false, reason: 'missing id' }
  await _delay(150)
  const store = _loadStore()
  const idx = store.findIndex(it => it.id === id)
  if (idx === -1) return { ok: false, reason: 'not found' }
  store.splice(idx, 1)
  _saveStore(store)
  return { ok: true }
}

// Optional: updateImage (not used here but handy)
export async function updateImage(id, patch = {}) {
  await _delay(150)
  const store = _loadStore()
  const idx = store.findIndex(it => it.id === id)
  if (idx === -1) return null
  const updated = { ...store[idx], ...patch }
  store[idx] = updated
  _saveStore(store)
  return updated
}

// 聊天历史相关函数 - 支持时间筛选
export async function getChatHistory(limit = 20, page = 1, dateFilter = 'all') {
  try {
    const params = new URLSearchParams({ 
      limit: limit.toString(), 
      page: page.toString(),
      dateFilter 
    })
    const res = await fetch(`/api/chat/history?${params}`)
    if (!res.ok) throw new Error('获取历史记录失败')
    const result = await res.json()
    
    console.log(`📡 [MockAPI] 获取聊天历史: ${result.conversations?.length || 0} 条, 筛选: ${dateFilter}`)
    
    return {
      conversations: result.conversations || [],
      total: result.total || 0,
      hasMore: result.hasMore !== false
    }
  } catch (err) {
    console.error('获取聊天历史失败:', err)
    return { conversations: [], total: 0, hasMore: false }
  }
}

export async function searchChatHistory(query, limit = 10) {
  try {
    const res = await fetch('/api/chat/search', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query, limit })
    })
    if (!res.ok) throw new Error('搜索历史记录失败')
    return res.json()
  } catch (err) {
    console.error('搜索聊天历史失败:', err)
    return { conversations: [] }
  }
}

export async function deleteChatConversation(id) {
  try {
    const res = await fetch(`/api/chat/history/${encodeURIComponent(id)}`, {
      method: 'DELETE'
    })
    if (!res.ok) throw new Error('删除对话失败')
    return res.json()
  } catch (err) {
    console.error('删除对话失败:', err)
    return { success: false }
  }
}

export async function clearChatHistory() {
  try {
    const res = await fetch('/api/chat/history', { method: 'DELETE' })
    if (!res.ok) throw new Error('清空历史记录失败')
    return res.json()
  } catch (err) {
    console.error('清空历史记录失败:', err)
    return { success: false }
  }
}

// 新增：向量数据库相似性搜索
export async function searchSimilarImages(imageFile) {
  try {
    const formData = new FormData()
    formData.append('image', imageFile)
    
    const res = await fetch('/api/images/similarity-search', {
      method: 'POST',
      body: formData
    })
    
    if (!res.ok) throw new Error('相似性搜索失败')
    const data = await res.json()
    return data.images || []
  } catch (err) {
    console.error('相似性搜索失败:', err)
    // 降级到本地搜索
    await _delay(500)
    return _loadStore().slice(0, 5)
  }
}

// 新增：AI智能打标签
export async function generateSmartTags(imageFile) {
  try {
    const formData = new FormData()
    formData.append('image', imageFile)
    
    const res = await fetch('/api/images/generate-tags', {
      method: 'POST',
      body: formData
    })
    
    if (!res.ok) throw new Error('AI标签生成失败')
    const data = await res.json()
    return data.tags || []
  } catch (err) {
    console.error('AI标签生成失败:', err)
    // 模拟AI标签生成
    await _delay(800)
    const mockTags = ['裂纹', '腐蚀', '油污', '磨损', '分层', '正常']
    return mockTags.slice(0, Math.floor(Math.random() * 3) + 1)
  }
}

// 新增：AI智能描述生成
export async function generateSmartDescription(imageFile) {
  try {
    const formData = new FormData()
    formData.append('image', imageFile)
    
    const res = await fetch('/api/images/generate-description', {
      method: 'POST',
      body: formData
    })
    
    if (!res.ok) throw new Error('AI描述生成失败')
    const data = await res.json()
    return data.description || ''
  } catch (err) {
    console.error('AI描述生成失败:', err)
    // 模拟AI描述生成
    await _delay(1000)
    const mockDescriptions = [
      '叶片表面存在明显的纵向裂纹，长度约15cm，位于叶片前缘位置',
      '叶片根部发现腐蚀痕迹，腐蚀面积约占总表面的5%',
      '叶片表面有轻微油污，可能影响空气动力学性能',
      '叶片边缘出现磨损现象，厚度减少约2mm',
      '复合材料出现分层现象，需要及时维修',
      '叶片表面状况良好，无明显缺陷'
    ]
    return mockDescriptions[Math.floor(Math.random() * mockDescriptions.length)]
  }
}

// 增强版检测和保存功能，集成AI智能处理
export async function detectAndSaveImageWithAI({ name, dataUrl }) {
  try {
    // 将dataUrl转换为File对象
    const response = await fetch(dataUrl)
    const blob = await response.blob()
    const file = new File([blob], name, { type: blob.type })
    
    // 并行调用AI服务
    const [tags, description] = await Promise.all([
      generateSmartTags(file),
      generateSmartDescription(file)
    ])
    
    // 模拟检测结果
    const detections = tags.filter(tag => tag !== '正常').map(tag => ({
      class: tag,
      confidence: 0.7 + Math.random() * 0.25,
      bbox: [
        Math.floor(Math.random() * 100),
        Math.floor(Math.random() * 100),
        Math.floor(Math.random() * 200) + 100,
        Math.floor(Math.random() * 200) + 100
      ]
    }))
    
    // 保存到本地存储
    const store = _loadStore()
    const id = `img_${Date.now()}_${Math.floor(Math.random() * 9999)}`
    const item = {
      id,
      name: name || id,
      dataUrl: dataUrl || '',
      url: '',
      tags: tags,
      description: description,
      detections: detections,
      createdAt: Date.now(),
      aiProcessed: true
    }
    
    // 同时保存到向量数据库
    await saveToVectorDB(item, file)
    
    store.unshift(item)
    _saveStore(store)
    return item
  } catch (err) {
    console.error('AI增强检测失败:', err)
    // 降级到普通检测
    return detectAndSaveImage({ name, dataUrl })
  }
}

// 新增：保存到向量数据库
async function saveToVectorDB(item, imageFile) {
  try {
    const formData = new FormData()
    formData.append('image', imageFile)
    formData.append('metadata', JSON.stringify({
      id: item.id,
      name: item.name,
      tags: item.tags,
      description: item.description,
      detections: item.detections,
      createdAt: item.createdAt
    }))
    
    const res = await fetch('/api/images/save-to-vector-db', {
      method: 'POST',
      body: formData
    })
    
    if (!res.ok) {
      console.warn('向量数据库保存失败')
    }
  } catch (err) {
    console.error('向量数据库保存失败:', err)
  }
}

// 新增：高级搜索功能，支持语义搜索
export async function advancedSearch({ query = '', tags = [], dateRange = 'all', sortBy = 'createdAt' }) {
  try {
    const res = await fetch('/api/images/advanced-search', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query, tags, dateRange, sortBy })
    })
    
    if (!res.ok) throw new Error('高级搜索失败')
    const data = await res.json()
    return data.images || []
  } catch (err) {
    console.error('高级搜索失败:', err)
    // 降级到本地搜索
    await _delay(300)
    let store = _loadStore()
    
    // 按标签筛选
    if (tags.length > 0) {
      store = store.filter(item => 
        Array.isArray(item.tags) && 
        tags.some(tag => item.tags.includes(tag))
      )
    }
    
    // 按查询词筛选
    if (query.trim()) {
      const qLower = query.toLowerCase()
      store = store.filter(item => 
        (item.name || '').toLowerCase().includes(qLower) ||
        (item.description || '').toLowerCase().includes(qLower) ||
        (Array.isArray(item.tags) && item.tags.join(',').toLowerCase().includes(qLower))
      )
    }
    
    // 按时间筛选
    if (dateRange !== 'all') {
      const now = Date.now()
      const ranges = {
        today: 24 * 60 * 60 * 1000,
        week: 7 * 24 * 60 * 60 * 1000,
        month: 30 * 24 * 60 * 60 * 1000
      }
      const timeThreshold = now - (ranges[dateRange] || 0)
      store = store.filter(item => (item.createdAt || 0) >= timeThreshold)
    }
    
    // 排序
    store.sort((a, b) => {
      if (sortBy === 'createdAt') {
        return (b.createdAt || 0) - (a.createdAt || 0)
      } else if (sortBy === 'name') {
        return (a.name || '').localeCompare(b.name || '')
      }
      return 0
    })
    
    return store
  }
}

// 新增：获取数据统计信息
export async function getDataStatistics() {
  try {
    const res = await fetch('/api/images/statistics')
    if (!res.ok) throw new Error('获取统计信息失败')
    return res.json()
  } catch (err) {
    console.error('获取统计信息失败:', err)
    // 使用本地数据计算统计
    await _delay(100)
    const store = _loadStore()
    
    const tagCounts = {}
    let defectCount = 0
    let normalCount = 0
    let aiProcessedCount = 0
    
    store.forEach(item => {
      if (item.aiProcessed) aiProcessedCount++
      
      if (Array.isArray(item.tags)) {
        item.tags.forEach(tag => {
          tagCounts[tag] = (tagCounts[tag] || 0) + 1
          if (tag !== '正常') defectCount++
        })
        if (item.tags.length === 0 || item.tags.includes('正常')) {
          normalCount++
        }
      }
    })
    
    return {
      total: store.length,
      defectCount,
      normalCount,
      aiProcessedCount,
      tagCounts,
      avgConfidence: store.reduce((sum, item) => {
        if (item.detections && item.detections.length > 0) {
          const avgConf = item.detections.reduce((s, d) => s + (d.confidence || 0), 0) / item.detections.length
          return sum + avgConf
        }
        return sum
      }, 0) / store.length || 0
    }
  }
}